<template>
  <div class="card" style="width: 60%; padding: 30px; margin: auto">
    <h3 style="text-align: center; margin-bottom: 20px">个人信息</h3>

    <el-form ref="formRef" :model="User.form" :rules="User.rules" label-width="120px">

      <!-- 账号 -->
      <el-form-item label="账号">
        <el-input v-model="User.form.username" disabled />
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="User.form.password" placeholder="请输入密码" :disabled="!isEditing" />
      </el-form-item>
      <!-- 上传简历按钮 -->
      <el-form-item label="简历">
        <div class="upload-container" :class="{'has-file': hasFileUploaded}">
          <el-upload ref="uploadRef" class="custom-upload" action="" :auto-upload="false" :on-change="handleFileChange"
            :show-file-list="false" accept=".doc,.docx" :limit="1" drag>
            <div class="upload-area" @click="triggerUpload">
              <div class="close-btn" v-if="hasFileUploaded" @click.stop="clearFile">
                <el-icon>
                  <Close />
                </el-icon>
              </div>

              <el-icon class="upload-icon">
                <UploadFilled />
              </el-icon>
              <p class="upload-text">点击上传，或将文件拖拽到此处</p>
              <p class="upload-tip">仅支持上传.docx 格式文件</p>

              <!-- 文件信息 -->
              <div class="file-info" v-if="hasFileUploaded">
                <el-icon class="success-icon">
                  <SuccessFilled />
                </el-icon>
                <span class="file-name">{{ fileName }}</span>
              </div>
            </div>
            <template #tip>
              <div class="upload-action">
                <el-button type="primary" class="upload-btn" @click="triggerUpload">开始上传</el-button>
              </div>
            </template>
          </el-upload>
        </div>
      </el-form-item>
      <!-- 姓名 -->
      <el-form-item label="姓名" prop="name">
        <el-input v-model="User.form.name" placeholder="请输入姓名" :disabled="!isEditing" />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="sex">
        <el-select v-model="User.form.sex" placeholder="请选择性别" :disabled="!isEditing">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="User.form.email" placeholder="请输入邮箱" :disabled="!isEditing" />
      </el-form-item>

      <!-- 电话 -->
      <el-form-item label="联系方式" prop="telephone">
        <el-input v-model="User.form.telephone" placeholder="请输入电话" :disabled="!isEditing" />
      </el-form-item>

      <!-- 教育背景 -->
      <el-form-item label="教育背景" prop="educationBackground">
        <el-input v-model="User.form.educationBackground" type="textarea" :rows="3" placeholder="请输入教育背景"
          :disabled="!isEditing" />
      </el-form-item>


      <!-- 上传后才显示的按钮 -->
      <!-- <div class="preview-toggle" v-if="hasFileUploaded">
        <el-button @click="isPreviewVisible = !isPreviewVisible" :type="isPreviewVisible ? 'primary' : 'info'"
          :icon="isPreviewVisible ? Minus : Plus" circle />
      </div> -->
      <!-- 预览内容区域 -->
      <!-- <transition name="fade">
        <div v-show="isPreviewVisible" class="preview-container">
          <div class="preview-content" v-if="previewContent">
            <h4 style="color: #606266; margin-top: 0;">简历内容预览：</h4>
            <div class="preview-body" v-html="previewContent"></div>
          </div>
          <div v-else class="preview-content">
            <p style="text-align: center; color: #999;">请上传 .docx 格式文件以查看预览内容</p>
          </div>
        </div>
      </transition> -->
      <!-- 学历 -->
      <el-form-item label="学历层次" prop="record">
        <el-select v-model="User.form.record" placeholder="请选择学历" :disabled="!isEditing">
          <el-option label="专科" :value="0" />
          <el-option label="本科" :value="1" />
          <el-option label="硕士" :value="2" />
          <el-option label="博士" :value="3" />
        </el-select>
      </el-form-item>
      <!-- 技能特长 -->
      <el-form-item label="技能特长" prop="skills">
        <el-input v-model="User.form.skills" type="textarea" :rows="5" placeholder="请输入技能特长" :disabled="!isEditing" />
      </el-form-item>

      <!-- 实习经历 -->
      <el-form-item label="实习经历" prop="internshipExperience">
        <el-input v-model="User.form.internshipExperience" type="textarea" :rows="5" placeholder="请输入实习经历"
          :disabled="!isEditing" />
      </el-form-item>

      <!-- 校园经历 -->
      <el-form-item label="校园经历" prop="campusExperience">
        <el-input v-model="User.form.campusExperience" type="textarea" :rows="5" placeholder="请输入校园经历"
          :disabled="!isEditing" />
      </el-form-item>

      <!-- 科技竞赛 -->
      <el-form-item label="科技竞赛" prop="techCompetition">
        <el-input v-model="User.form.techCompetition" type="textarea" :rows="5" placeholder="请输入参与的科技竞赛"
          :disabled="!isEditing" />
      </el-form-item>

      <!-- 自我评价 -->
      <el-form-item label="自我评价" prop="selfEvaluation">
        <el-input v-model="User.form.selfEvaluation" type="textarea" :rows="5" placeholder="请输入自我评价"
          :disabled="!isEditing" />
      </el-form-item>

      <!-- 分隔线和提示文字 -->

     <el-divider style="border-color: red;" />
      <el-form-item>

        <div style="color: #ff0000; font-size: 14px; margin-top: -20px;">
          以下字段需要用户手动添加
        </div>
      </el-form-item>
      <!-- 薪资期望 -->
      <el-form-item label="薪资期望" prop="salary">
        <el-input-number v-model="User.form.salary" :min="0" :max="100000" label="请输入期望薪资" :disabled="!isEditing" />
      </el-form-item>

      <!-- 所在城市（支持多选） -->
      <el-form-item label="所在城市" prop="city">
        <el-select v-model="User.form.cityList" multiple placeholder="请选择城市" :disabled="!isEditing">
          <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 福利待遇 -->
      <el-form-item label="福利待遇" prop="benefits">
        <el-input v-model="User.form.benefits" placeholder="请输入期望的福利待遇" :disabled="!isEditing" />
      </el-form-item>
      <!-- 办公时间（拆分成上下班） -->
      <el-form-item label="办公时间" prop="officeHours">
        <el-time-picker v-model="User.form.startTime" value-format="HH:mm" format="HH:mm" placeholder="开始时间"
          :disabled="!isEditing" />
        <span style="margin: 0 10px">至</span>
        <el-time-picker v-model="User.form.endTime" value-format="HH:mm" format="HH:mm" placeholder="结束时间"
          :disabled="!isEditing" />
      </el-form-item>

      <!-- 注册时间 -->
      <el-form-item label="注册时间">
        <el-input v-model="User.form.registerTime" disabled />
      </el-form-item>

      <!-- 最后更新时间 -->
      <el-form-item label="最后更新时间">
        <el-input v-model="User.form.updateTime" disabled />
      </el-form-item>

      <!-- 按钮区域 -->
      <el-form-item style="text-align: center">
        <el-button @click="toggleEdit" type="primary" v-if="!isEditing">修改信息</el-button>
        <el-button @click="updateUser" type="success" v-else>提交信息</el-button>
        <el-button @click="router.back()" plain>返回</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { parseJwt, getToken } from '@/utils/auth'
import * as mammoth from 'mammoth' // 导入 mammoth.js
const previewContent = ref('')
const isPreviewVisible = ref(false) // 控制是否显示预览
import { Plus, Minus } from '@element-plus/icons-vue'
const formRef = ref()
import { UploadFilled } from '@element-plus/icons-vue'

// 添加文件名引用
const fileName = ref('')
const hasFileUploaded = ref(false) // 控制按钮显示状态

// 清空文件的方法
const clearFile = () => {
  // 重置上传组件
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  
  // 重置状态
  hasFileUploaded.value = false
  fileName.value = ''
  previewContent.value = ''
  isPreviewVisible.value = false
  
  // 清除预览内容
  ElMessage.success('已清除上传的简历，可以重新上传')
}
// 添加上传组件的引用
const uploadRef = ref(null)

// 触发上传的方法
const triggerUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.$el.querySelector('input[type="file"]').click()
  }
}
// 城市选项（从后端获取或硬编码）
const cityOptions = [
  { label: '北京', value: '北京' },
  { label: '上海', value: '上海' },
  { label: '天津', value: '天津' },
  { label: '重庆', value: '重庆' },
  { label: '河北', value: '河北' },
  { label: '山西', value: '山西' },
  { label: '辽宁', value: '辽宁' },
  { label: '吉林', value: '吉林' },
  { label: '黑龙江', value: '黑龙江' },
  { label: '江苏', value: '江苏' },
  { label: '浙江', value: '浙江' },
  { label: '安徽', value: '安徽' },
  { label: '福建', value: '福建' },
  { label: '江西', value: '江西' },
  { label: '山东', value: '山东' },
  { label: '河南', value: '河南' },
  { label: '湖北', value: '湖北' },
  { label: '湖南', value: '湖南' },
  { label: '广东', value: '广东' },
  { label: '海南', value: '海南' },
  { label: '四川', value: '四川' },
  { label: '贵州', value: '贵州' },
  { label: '云南', value: '云南' },
  { label: '陕西', value: '陕西' },
  { label: '甘肃', value: '甘肃' },
  { label: '青海', value: '青海' },
  { label: '台湾', value: '台湾' },
  { label: '内蒙古', value: '内蒙古' },
  { label: '广西', value: '广西' },
  { label: '西藏', value: '西藏' },
  { label: '宁夏', value: '宁夏' },
  { label: '新疆', value: '新疆' },
  { label: '香港', value: '香港' },
  { label: '澳门', value: '澳门' }
];

// 学生信息（默认只读）
const User = reactive({
  form: {
    username: '',
    password: '',
    name: '',
    sex: '',
    email: '',
    telephone: '',
    educationBackground: '', // 替换 school
    record: null,
    salary: 0,
    cityList: [], // 支持多选
    benefits: '',
    startTime: '', // 上班时间
    endTime: '',   // 下班时间
    registerTime: '',
    updateTime: '',
    skills: '',                // 技能特长
    internshipExperience: '',  // 实习经历
    campusExperience: '',      // 校园经历
    techCompetition: '',       // 科技竞赛
    selfEvaluation: ''         // 自我评价
  },
  rules: {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
    ],
    telephone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
    educationBackground: [{ required: true, message: '请输入教育背景', trigger: 'blur' }],
    record: [{ required: true, message: '请选择学历', trigger: 'change' }]
  }
});

// 使用 ref 控制编辑状态
const isEditing = ref(false)

// 模拟从 JWT 解析用户信息并加载数据
const loadUserInfo = () => {
  const token = getToken();
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }

  const userInfo = parseJwt(token);
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录');
    router.push('/login');
    return;
  }

  axios.get(`/api/student/info/${userInfo.id}`, {
    headers: {
      Authorization: 'Bearer ' + token
    }
  }).then(res => {
    if (res.status === 304) {
      const cachedData = JSON.parse(localStorage.getItem('cachedStudentData'));
      if (cachedData) {
        populateForm(cachedData);
      } else {
        ElMessage.error('缓存数据缺失，请刷新页面');
      }
    } else if (res.data && res.data.code === 200 && res.data.data) {
      populateForm(res.data.data);
      localStorage.setItem('cachedStudentData', JSON.stringify(res.data.data));
    } else {
      ElMessage.error('获取用户信息失败');
    }
  }).catch(err => {
    console.error('请求失败:', err);
    ElMessage.error('网络异常，请重试');
  });
};
const populateForm = (data) => {
  User.form.username = data.username;
  User.form.password = data.password; 
  User.form.name = data.name;
  User.form.sex = data.sex;
  User.form.email = data.email;
  User.form.telephone = data.telephone;
  User.form.educationBackground = data.educationBackground;
  User.form.record = data.record;
  User.form.salary = data.salary;
  User.form.cityList = data.city ? data.city.split(',') : [];
  User.form.benefits = data.benefits;
  const officeHours = data.officeHours?.split(' - ');
  User.form.startTime = officeHours?.[0] || '';
  User.form.endTime = officeHours?.[1] || '';
  User.form.registerTime = formatDate(data.registerTime);
  User.form.updateTime = formatDate(data.updateTime);

  // 新增字段填充
  User.form.skills = data.skills || '';
  User.form.internshipExperience = data.internshipExperience || '';
  User.form.campusExperience = data.campusExperience || '';
  User.form.techCompetition = data.techCompetition || '';
  User.form.selfEvaluation = data.selfEvaluation || '';
};

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 更新用户信息
const updateUser = async () => {
  const userInfo = parseJwt()
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  const dataToSend = {
    id: userInfo.id,
    username: User.form.username,
    password: User.form.password, 
    name: User.form.name,
    sex: User.form.sex,
    email: User.form.email,
    telephone: User.form.telephone,
    educationBackground: User.form.educationBackground,
    record: User.form.record,
    salary: User.form.salary,
    city: User.form.cityList.join(','), // 合并城市列表为字符串
    benefits: User.form.benefits,
    officeHours: `${User.form.startTime} - ${User.form.endTime}`,
    // 新增字段
    skills: User.form.skills,
    internshipExperience: User.form.internshipExperience,
    campusExperience: User.form.campusExperience,
    techCompetition: User.form.techCompetition,
    selfEvaluation: User.form.selfEvaluation
  }

  try {
    const res = await axios.put('http://localhost:8080/api/student/update', dataToSend, {
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      localStorage.setItem('user', JSON.stringify(User.form))
      toggleEdit() // 返回只读模式
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('请求错误:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录状态异常，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('网络异常，请重试')
    }
  }
}
// 处理Word文件上传
const handleFileChange = (file) => {
  if (!file.raw) return;
const educationMap = {
  '专科': 0,
  '本科': 1,
  '硕士': 2,
  '博士': 3
};
  // 检查文件类型
  const isWordFile = file.raw.type === 'application/msword' || 
                     file.raw.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                     file.name.endsWith('.doc') || 
                     file.name.endsWith('.docx');

  if (!isWordFile) {
    ElMessage.error('请上传Word文档(.doc或.docx)');
    return;
  }
 if (file.name.endsWith('.docx')) {
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const arrayBuffer = e.target.result;
        const result = await mammoth.convertToHtml({ arrayBuffer });
        previewContent.value = result.value; // 提取 HTML 内容
      } catch (err) {
        console.error('预览解析失败:', err);
        previewContent.value = '<p>无法解析文档，请检查文件格式</p>';
      }
    };
    reader.readAsArrayBuffer(file.raw);
  } else {
    previewContent.value = '<p>仅支持 .docx 格式预览</p>';
  }
    fileName.value = file.name
  hasFileUploaded.value = true
  const formData = new FormData();
  formData.append('file', file.raw); 

  axios.post('/api/doc/upload/student', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: 'Bearer ' + getToken()
    }
  })
  .then(response => {
    console.log('上传成功:', response.data);
    if (response.data.success) {
      hasFileUploaded.value = true;
      const resumeData = response.data.data;

      // 直接赋值（无需查找字段）
      if (resumeData.name) User.form.name = resumeData.name;
      if (resumeData.sex) User.form.sex = resumeData.sex;
      if (resumeData.telephone) User.form.telephone = resumeData.telephone;
      if (resumeData.email) User.form.email = resumeData.email;
      if (resumeData.educationBackground) User.form.educationBackground = resumeData.educationBackground;
      if (resumeData.skills) User.form.skills = resumeData.skills;
      if (resumeData.internshipExperience) User.form.internshipExperience = resumeData.internshipExperience;
      if (resumeData.campusExperience) User.form.campusExperience = resumeData.campusExperience;
      if (resumeData.techCompetition) User.form.techCompetition = resumeData.techCompetition;
      if (resumeData.selfEvaluation) User.form.selfEvaluation = resumeData.selfEvaluation;
      if (resumeData.record) User.form.record = resumeData.record;
      if (resumeData.record) {
        const numericValue = parseInt(resumeData.record, 10);
        if (!isNaN(numericValue)) {
          User.form.record = numericValue;
        } else {
          console.warn('record 不是有效的数字:', resumeData.record);
        }
      }
      if (!isEditing.value) isEditing.value = true;
      ElMessage.success('简历信息已自动填充');
    } else {
      ElMessage.error('解析失败: ' + response.data.message);
    }
  })
    .catch(error => {
      console.error('上传失败:', error);
    ElMessage.error('简历解析失败，请重试');
  });
  
};

// 工具方法：统一日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return ''

  // 处理 LocalDateTime 字符串格式："2025-04-07T14:30:00"
  const date = new Date(dateStr)

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从 0 开始
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  loadUserInfo()
})

</script>
<style scoped>
.card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: #fff;
}

/* 上传区域样式 */
.upload-container {
  position: relative;
}

.custom-upload :deep(.el-upload) {
  width: 100%;
}

.custom-upload :deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
  position: relative; /* 修复关闭按钮定位的关键 */
}

.custom-upload :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}


.upload-area {
  text-align: center;
  padding: 20px;
}

.upload-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin: 5px 0;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin: 5px 0;
}

.upload-action {
  margin-top: 15px;
  text-align: center;
}

.upload-btn {
  width: 120px;
}
/* 关闭按钮 - 修复定位 */
.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #f56c6c;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background-color: #f78989;
  transform: scale(1.1);
}

/* 文件信息样式 */
.file-info {
  margin-top: 15px;
  padding: 8px;
  background-color: #f0f9eb;
  border-radius: 4px;
  display: flex;
  align-items: center;
  width: 80%;
  justify-content: center;
}

.success-icon {
  color: #67c23a;
  margin-right: 8px;
}

.file-name {
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 有文件时修改样式 */
.has-file .el-upload-dragger {
  background-color: #f5f7fa;
  border-color: #e1f3d8;
}

/* 预览区域样式 */
.preview-toggle {
  text-align: center;
  margin: 15px 0;
  transition: opacity 0.3s ease;
}

.preview-toggle .el-button {
  width: 40px;
  height: 40px;
  font-size: 20px;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.preview-container {
  background: #f9fafc;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.preview-content {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  word-break: break-all;
}

.preview-body {
  padding-left: 10px;
  border-left: 2px solid #e4e7ed;
}

</style>